<template>
  <view class="container whov">
    <IFexHeaderMain>
      <template #header>
        <IHeader>设备详情</IHeader>
        <view class="status-bar">
          <view v-for="(item, index) in tarList" :key="index" class="status-item" :style="{ background: item.color }">
            <text>{{ item.label }}</text>
          </view>
        </view>
      </template>
      <view class="wh_auto" style="background-color: #f5f7fa">
        <view class="device-grid">
          <view v-for="(item, index) in dataList" :key="index" :class="changeData.id == item.id ? 'active' : ''" class="device-cell" @click="changeRowFun(item)" :style="{ background: getCellColor(item) }">
            <text class="cell-text">{{ item.ip }}</text>
          </view>
        </view>
        <view class="wrapper whov" v-if="dataList.length === 0">
          <view style="width: 50%;height: 50%;" v-if="qrCode">
            <image :src="qrCode" mode="widthFix" class="logo-img"></image>
          </view>
          <view class="empty-state" v-else> 暂无数据 </view>
        </view>
      </view>

      <template #footer>
        <view class="bottom-bar">
          <view v-for="(item, index) in bottomList" :key="index" class="bottom-item" @click="item.callback">
            <text class="bottom-text">{{ item.label }}</text>
          </view>
        </view>
      </template>
    </IFexHeaderMain>
    <uni-popup ref="popupRef" type="dialog">
      <uni-popup-dialog cancelText="取消" confirmText="设置" title="请选择柜子状态" @confirm="handlerConfirm">
        <view class="checkbox-container">
          <uni-data-checkbox mode="tag" v-model="status" :localdata="tarList.map((item) => ({ text: item.label, value: item.status }))" class="custom-checkbox"></uni-data-checkbox>
        </view>
      </uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script setup lang="ts" name="index">
  import { nextTick, onMounted, ref } from 'vue'
  import IFexHeaderMain from '@/components/container/IFexHeaderMain.vue'
  import IHeader from '@/components/container/IHeader.vue'
  import { onLoad } from '@dcloudio/uni-app'
  import { getCabinetStatus, getDeviceCabinetDetails, selectStatus, setCabinetStatus, unlock, unlockAll } from '@/api/zmanager/device'
  import useToastMsg from '@/hooks/sysMsg'
  const toastMsg = useToastMsg()
  const popupRef = ref()
  const tarList = ref<any[]>([])
  const changeData = ref<any>({})
  const status = ref<string>('')
  const counterNo = ref('')
  const qrCode = ref<any>(null)
  const bottomList = ref([
    {
      label: '开锁',
      callback: async () => {
        if (changeData.value.id) {
          toastMsg.showLoading()
          const result = await unlock(changeData.value.id)
          if (result) {
            toastMsg.showToast(`${changeData.value.doorNo}：开锁成功`)
            init()
          } else {
            toastMsg.hideLoading()
          }
        } else {
          toastMsg.showToast('请先选择柜子')
        }
      },
    },
    {
      label: '全部开锁',
      callback: async () => {
        toastMsg.showLoading()
        const result = await unlockAll(counterNo.value)
        if (result) {
          toastMsg.showToast(`开锁成功`)
          init()
        } else {
          toastMsg.hideLoading()
        }
      },
    },
    {
      label: '查询状态',
      callback: async () => {
        if (changeData.value.id) {
          toastMsg.showLoading()
          const result = await selectStatus(changeData.value.id)
          if (result) {
            const statsRow = tarList.value.find((item) => result.data == item.status)
            toastMsg.showToast(`${changeData.value.doorNo}的状态为：${statsRow.label}`)
          } else {
            toastMsg.hideLoading()
          }
        } else {
          toastMsg.showToast('请先选择柜子')
        }
      },
    },
    {
      label: '设置',
      callback: () => {
        if (changeData.value.id) {
          handlePopClick()
        } else {
          toastMsg.showToast('请先选择柜子')
        }
      },
    },
    // { label: '清柜', callback: () => {} },
    // { label: '一键清柜', callback: () => {} },
  ])
  const dataList = ref<any[]>([])
  onLoad((options: any) => {
    counterNo.value = options.counterNo
  })

  onMounted(() =>
    nextTick(async () => {
      const result = await getCabinetStatus()
      if (result) {
        tarList.value = result.data.cabinetStatus.map((item: any) => ({ label: item.dictLabel, color: item.cssClass, status: item.dictValue }))
        await init()
      }
    }),
  )
  const init = async () => {
    toastMsg.showLoading()
    const result = await getDeviceCabinetDetails(counterNo.value)
    if (result) {
      qrCode.value = result.data.logoQrCode || null
      dataList.value = result.data.deviceCabinetList
    }
    toastMsg.hideLoading()
  }
  const changeRowFun = (data: any) => {
    changeData.value = changeData.value.id == data.id ? { id: '' } : data
  }
  // 根据编号获取方格背景色
  const getCellColor = (data: any) => {
    const target = tarList.value.find((item) => data.cabinetStatus === item.status)
    return target ? target.color : tarList.value[0].color
  }
  const handlePopClick = (type = 'open') => (type == 'close' ? popupRef.value.close() : popupRef.value.open())
  const handlerConfirm = async () => {
    toastMsg.showLoading()
    const result = await setCabinetStatus(changeData.value.id, status.value)
    if (result) {
      toastMsg.showToast(`${changeData.value.doorNo}：状态设置成功`)
      init()
    } else {
      toastMsg.hideLoading()
    }
  }
</script>

<style scoped lang="scss">
  /* 状态标识栏样式保持不变 */
  .status-bar {
    display: flex;
    padding: 10rpx 20rpx;
    background-color: #fff;
    flex-wrap: wrap;
    gap: 20rpx;

    .status-item {
      font-size: 24rpx;
      flex: 1;
      color: #ffffff;
      padding: 6rpx 0;
      border-radius: 8rpx;
      font-weight: 700;
      text-align: center;
    }
  }

  /* 设备方格布局（核心：一行6个平均分配） */
  .device-grid {
    display: flex;
    flex-wrap: wrap;
    padding: 10rpx;
    /* 关键：通过负margin抵消子元素的间距，确保总宽度不溢出 */
    margin: 0 -4rpx;
  }

  .device-cell {
    /* 计算逻辑：100%/6列 = 16.666%，减去左右各4rpx间距 */
    width: calc(16.666% - 8rpx);
    aspect-ratio: 1 / 1; /* 保持正方形 */
    margin: 0 4rpx 8rpx; /* 水平间距8rpx（左右各4rpx），垂直间距8rpx */
    border-radius: 6rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 24rpx;
    color: #fff;
    font-weight: 500;
    box-shadow: 0 1rpx 3rpx rgba(0, 0, 0, 0.1);
    box-sizing: border-box; /* 确保padding和border不影响宽度计算 */
  }

  /* 底部操作栏样式保持不变 */
  .bottom-bar {
    display: flex;
    background-color: #fff;
    border-top: 1px solid #ebeef5;

    .bottom-item {
      flex: 1;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 80rpx;
      font-size: 26rpx;
      color: #333;
      border-right: 1px solid #ebeef5;

      &:last-child {
        border-right: none;
      }
    }
  }
  .active {
    border: 2px solid red;
  }
  .checkbox-container {
    padding: 15rpx 20rpx;
    background-color: #fff;
  }

  /* 自定义复选框标签样式 */
  .custom-checkbox {
    /* 让标签平均分配宽度 */
    display: flex;
    width: 100%;
    gap: 10rpx; /* 标签之间的间距 */
  }

  /* 调整每个标签的样式（变大且平均分配） */
  ::v-deep .uni-data-checkbox__tag {
    flex: 1; /* 平均分配父容器宽度 */
    height: 80rpx; /* 增大高度 */
    line-height: 80rpx; /* 文字垂直居中 */
    font-size: 28rpx; /* 增大字体 */
    padding: 0 10rpx; /* 调整内边距 */
    border-radius: 8rpx; /* 圆角优化 */
    margin: 0; /* 清除默认外边距 */
  }

  /* 选中状态的标签样式增强 */
  ::v-deep .uni-data-checkbox__tag--active {
    font-weight: bold;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  }
</style>
